var debugServer = false;

//获取服务器URL
function isDebugServer() {
    debugServer = pageConfig.debug;
}

isDebugServer();

var liveConfig = {
        chatNumUrl: pageConfig.folderUrl + '/php/chatNum.php',
        configUrl: pageConfig.folderUrl + '/php/getLiveConfig.php',
        onLineNum: pageConfig.lcServerUrl + '/php/online.php',
        getConfig: function () {
            return (debugServer) ? this.debug : this.resele;
        }
    },
    /************************************************************************
     * 加载模块
     ************************************************************************/
    loadModule = {
        config: {scripts: []},
        loadScriptItem: function (url, callback) {
            var script = document.createElement_x("script")
            script.type = "text/javascript";
            if (script.readyState) { //IE
                script.onreadystatechange = function () {
                    if (script.readyState == "loaded" ||
                        script.readyState == "complete") {
                        script.onreadystatechange = null;
                        callback();
                    }
                };
            } else { //Others: Firefox, Safari, Chrome, and Opera
                script.onload = function () {
                    callback();
                };
            }
            script.src = url;
            document.body.appendChild(script);
        },
        loadScript: function (index, callback) {
            var self = this,
                sz = self.config.scripts;
            if (index >= sz.length)
                return;
            self.loadScriptItem(sz[index++], function () {
                if (index >= sz.length)
                    callback();
                else
                    setTimeout(function () {
                        self.loadScript(index, callback);
                    }, 1);
            });
        }
    },
    /************************************************************************
     用        户
     *************************************************************************/
    userAccount = {
        port: {
            msgCounter: liveConfig.chatNumUrl,
            params: {id: 1,}//onLineNum:
        },
        nicknamekey: 'vr_user_nick_name',
        nickminlen: 4,
        uidKey: 'vr_user_id',
        uidLen: 8,
        cookTime: 3600 * 12,
        nicknameprifx: '游客',
        sendmsgtime: 0,
        getOLTime: 0,
        //格式化用户编号ID
        format: function (num, n) {
            /*num = num + '';
            if (n > num.length || !window.cnum) {
                window.cnum = '';
                for(var i=0;i<=n;i++)
                    window.cnum += '0';
                if (n < num.length)
                    n = num.length;
                num = window.cnum + num;
                num = num.slice(num.length - n);
            }*/
            return num;
        },
        setUserNickName: function (usercount) {//设置用户昵称
            nk = getCookie(this.nicknamekey);//使用cookie里的用户昵称
            if (nk == null) {
                nk = this.nicknameprifx + this.format(usercount, this.nickminlen); //用户呢称，可以使用网站或微信等得到用户再取相应值
                setCookie(this.nicknamekey, nk, this.cookTime);
                window.nickname = nk;
            }
        },
        getUserNickName: function () {//获取用户昵称
            var nk = window.nickname;
            if (nk && nk != '')
                return nk;
            nk = getCookie(this.nicknamekey);//使用cookie里的用户昵称
            if (nk == null)
                nk = '游客';
            window.nickname = nk;
            return nk;
        },
        getUID: function () {//获取用户ID
            var uid = getCookie(this.uidKey);//使用cookie里的用户ID
            if (uid == null) {
                uid = generateUID(this.uidLen);//用户的ID，可以使用网站或微信等得到用户再生成相应ID
                setCookie(this.uidKey, uid, this.cookTime);
            }
            window.uid = uid;
            return uid;
        },
        getSendMsgOrder: function (callback) {
            var self = this;
            if (!userAccount.shendMsgShake())
                return;
            var data = {debug: (debugServer) ? 1 : 0,}
            data = $.extend(data, self.port.params);
            $.ajax({
                type: "post",
                url: self.port.msgCounter,
                async: true,
                data: data,
                dataType: 'json',
                success: function (result) {
                    if (result.code == 200) {
                        if (typeof callback == 'function')
                            callback(self.nicknameprifx + result.data);
                    } else {
                        console.log('get Send Msg Order result status', result);
                    }
                },
                error: function (e) {
                    console.log('get Send Msg Order error', e);
                }
            });
        },
        shendMsgShake: function () {
            var self = this,
                st = Date.parse(new Date());
            if (st - self.sendmsgtime > 500) {
                self.sendmsgtime = st;
                return true;
            } else {
                return false;
            }
        },
        getOnLineNum: function (callback) {
            var t = Date.parse(new Date());
            if ((t - this.getOLTime) < 60 * 1000)
                return;
            this.getOLTime = t;
            $.ajax({
                type: "post",
                url: liveConfig.onLineNum,
                async: true,
                dataType: 'json',
                success: function (result) {
                    if (result.code == 200) {
                        if (typeof callback == 'function') {
                            callback(result.data);
                        }
                    } else {
                        console.log('get on num reuslt', result);
                    }
                },
                error: function (e) {
                    //alert('get live config error' + JSON.stringify(e));
                    console.log('get live config error', e);
                }
            });
        },
    },
    /*****************************************************************
     * 使用弹幕
     */
    useBarrage = {
        init: function (linehight, fontsize, fontsizeunit) {
            if (pageConfig.barrage.use) {
                function waitEleInit() {
                    var config = {
                        name: 'cc_yd2_barrage',					//标识名称
                        id: 'cc_yd2_barrage',
                        eles: {hanging: pageConfig.barrage.ele},
                        msg: {
                            fontlinesize: linehight,	//文字行高度
                            fontsize: fontsize,	//字体大小
                            fontsizeunit: fontsizeunit,//文字大小单位
                        }, cmodel: 0,	//直播
                        run: {
                            model: 0,
                            sendMsgSpeendTime: 500//调试时发送消息速度
                        }
                    };
                    if ($(config.eles.hanging).length == 0) {
                        setTimeout(function () {
                            waitEleInit();
                        }, 100);
                        return;
                    }
                    barrage.init(config);
                    barrage.run(true);
                    $('.dm').on('click', function () {
                        if ($(this).hasClass('open')) {
                            barrage.run(true);
                            $(this).removeClass('open');
                        } else {
                            barrage.run(false);
                            $(this).addClass('open');
                        }
                    });
                }

                setTimeout(function () {
                    waitEleInit();
                }, 100);
            }
        },
        popMsg: function (msg) {
            if (pageConfig.barrage.use)
                barrage.popMsg(msg);
        }
    }
/**************************************************************
 *
 *                        一些基础功能
 *
 *************************************************************/
base = {
    imgNoFind: function () {
        var img = event.srcElement;
        img.src = "images/visitor.jpg";
        img.onerror = null;
    },
}


var timerSend = 5, isclick = 0;

function sendTimeer() {
    if (timerSend > 0) {
        timerSend--;
        isclick = 1;
        setTimeout(function () {
            sendTimeer()
        }, 1000)
    } else {
        timerSend = 5;
        isclick = 0
    }
}

function live_pc() {
    var selsctBox = function (tag) {
        if (tag == 'msg') {
            $(".msg-box").css("display", "block");
            $(".answer-box").css("display", "none");
            $("#msg").css("background-color", "#00479D");
            $("#msg").css("color", "white");
            $("#msg").css("border-color", "#00479D");
            $("#answer").css("background-color", "");
            $("#answer").css("color", "#666666");
            $("#answer").css("border-color", "#666666");
        } else {
            $(".msg-box").css("display", "none");
            $(".answer-box").css("display", "block");
            $("#msg").css("background-color", "");
            $("#msg").css("color", "#666666");
            $("#msg").css("border-color", "#666666");
            $("#answer").css("background-color", "#00479D");
            $("#answer").css("color", "white");
            $("#answer").css("border-color", "#00479D");
        }
    };

    $('.bottom-other').css("display", "");


    $('#msg').click(function () {
        selsctBox("msg");
    });

    var llConfig = liveConfig.getConfig();
    var lids = llConfig.lids;
    pid = (pid) ? pid : 0;
    if (pid == null) {
        console.log('请设定默认播放资源');
    }
    //设置播放器
    new ysyPlayer({
        playerid: 'player', //放入播放器的容器元素的ID
        appid: llConfig.appid,
        lid: lids[pid].id,
        live: lids[pid].live,
        vr: lids[pid].vr,
        setOptions: {
            width: '100%', //播放器的宽度
            height: '100%', //播放器的高度
            poster: 'http://e.changan.com.cn/eado-xt2018_2/images/pcxt/pc/yd_pc.jpg',
            autostart: lids[pid].autostart,
            errorMsg: '  '
        }
    });

    //聊天用户接入例子
    var uid = userAccount.getUID();
    var logourl = 'images/visitor.jpg'; //用户头像，可以使用网站或微信等得到用户再取相应值
    var page = 0;
    var pageFlag = true;
    var pageCount = 20;
    var $scrollbar = $('#scrollbar');
    $(document).ready(function () {
        $scrollbar.tinyscrollbar({thumbSize: 25});
    });


    $('html,body').on('click', '.msg-send-btn', function () {
        // $('input[name=ct]').val('');
        var ctcontent = $('input[name=ct]').val();
        var ct = msgFilter(ctcontent);
        if ($.trim($('input[name=ct]').val()) == '')
            return false;
        $('input[name=ct]').val('');
        if (isclick == 1 || timerSend < 10 || ct.indexOf('*') >= 0) {
            userAccount.getSendMsgOrder(function (resultUName) {
                var uname = resultUName;
                // var uname = userAccount.getUserNickName();
                var $barrageMsg = $('.barrage-msg');
                var str = '<li>';
                str += '<div class="barrage-msg-user"><b>' + uname + '</b>：<span class="barrage-msg-word">' + ctcontent + '</span></div>';
                str += '</li>';
                $barrageMsg.append(str);
                useBarrage.popMsg(ctcontent);//弹幕输出消息
                $('body').removeClass('noselect');
                $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                $scrollbar.data("plugin_tinyscrollbar").update('bottom');
                return false;
            })
            return false;
        }
        sendTimeer();
        //发消息的时候为了保证发送的json完整，用户的昵称中特殊符号需要转义

        $.get('php/ip.php', {}, function (res) {

            userAccount.getSendMsgOrder(function (resultUName) {
                var uname = resultUName;
                // var uname = userAccount.getUserNickName();
                //userAccount.getUserNickName()
                var $barrageMsg = $('.barrage-msg');
                var str = '<li>';
                str += '<div class="barrage-msg-user"><b>' + uname + '</b>：<span class="barrage-msg-word">' + ct + '</span></div>';
                str += '</li>';
                $barrageMsg.append(str);
                if (res.code == 200) {
                    ysyChat.sendMessage({
                        type: 'msg', content: ct.substr(0, 50) + '-{ip}-' + res.ip,
                        userdata: '{"exct":{"nk":"' + uname + '","logourl":"' + window.logourl + '","uid":"' + window.uid + '"}}',//可以自行加入更多的自定义属性用于传输
                    });
                } else {
                    useBarrage.popMsg(ct.substr(0, 50));//弹幕输出消息
                }
                $('body').removeClass('noselect');
                $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                $scrollbar.data("plugin_tinyscrollbar").update('bottom');
            });
        }, 'json')

    });
    $scrollbar.bind("move", function () {
        var thumbTop = parseInt($scrollbar.find('.thumb').css('top'));
        if (thumbTop == 0 && pageFlag == true)
            $('.msg-page-a').show();
        else
            $('.msg-page-a').hide();
        var scrollbarHeight = $scrollbar.find('.scrollbar').height();
        var barrageMsgTop = parseInt($scrollbar.find('.barrage-msg').position().top);
        var barrageMsgHeight = parseInt($scrollbar.find('.barrage-msg').css('height'));
        $('body').addClass('noselect');
        if (barrageMsgHeight + barrageMsgTop == scrollbarHeight) {
            $('body').removeClass('noselect');
            $('.barrage-more').attr('data-noselect', '0').html('暂无最新消息').hide();
        }
    });
    $('.msg-page-a').on('click', function () {
        if (page != 0)
            getOldCommentInfo();
    });
    $('.barrage-more').on('click', function () {
        $('body').removeClass('noselect');
        $(this).attr('data-noselect', '0').html('暂无最新消息').hide();
        $scrollbar.data("plugin_tinyscrollbar").update('bottom');
    });

    function quotationMarks(str) {
        str = str.replace(/\\/g, '\\\\');
        str = str.replace(/"/g, '\\\"');
        return str;
    };

    function getCommentInfo() {
        var $barrageMsg = $('.barrage-msg');
        ysyChat.init({
            "appid": llConfig.appid, "uid": uid, "topic": llConfig.topic,
        }, function (data) {
            if (data.attribute) {
                var watched_count = data.attribute.watched_count;//总参与人数
                var watching_count = data.attribute.watching_count;//当前参与人数
                userAccount.setUserNickName(watched_count);//根据人数设置用户昵称
                userAccount.getOnLineNum(function (count) {
                    $('#watch-count').text(count);
                });
                if (page == 0)
                    getOldCommentInfo();
            }
            if (data.type == 'msg' || data.type == 'redpack' || data.type == 'gift') {
                var data = JSON.parse(data.content);
                var userdata = data.userdata;
                var str = "";
                if (userdata.exct && userdata.exct != null && userdata.exct != undefined) {
                    var nk = userdata.exct.nk;
                    var uid = userdata.exct.uid;
                    var logourl = userdata.exct.logourl;
                    var context = data.context;
                    context = context.split('-{ip}-');
                    context = context[0];
                    context = msgFilter(context);
                    useBarrage.popMsg(context);//弹幕输出消息
                    if (uid != window.uid) {
                        str += '<li>';
                        str += '<div class="barrage-msg-user"><b>' + nk + '</b>：<span class="barrage-msg-word">' + context + '</span></div>';
                        str += '</li>';
                    } else {
                        $('body').removeClass('noselect');
                    }
                }
                $barrageMsg.append(str);
                var oldnoselect = parseInt($('.barrage-more').attr('data-noselect'));//评论框滚动条置低
                if ($('body').hasClass('noselect')) {
                    var newnoselect = oldnoselect + 1;
                    $('.barrage-more').html(newnoselect + '条新消息').show();
                    $('.barrage-more').attr('data-noselect', newnoselect);
                } else {
                    $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                    $scrollbar.data("plugin_tinyscrollbar").update('bottom');
                }
                return false;
            }
            if (data.type == 'system' || data.type == 'vote' || data.type == 'questionnaire') {
                var data = JSON.parse(data.content);
                if ('refresh' != data.refresh)
                    return;
                var tmp = Math.floor(Math.random() * 5 + 1) * 1000;
                setTimeout(function () {
                    window.location.reload();
                }, tmp);
            }
        })
    };

    function getOldCommentInfo() {
        var $barrageMsg = $('.barrage-msg');
        if (pageFlag == null || pageFlag == false)
            return;
        ysyChat.gethistorymsg({"start": page, "count": pageCount, "type": "msg,redpack,gift"},
            function (data) {
                if (data.list == null)
                    return;
                var list = data.list;
                var count = data.count;
                if (count < pageCount) {
                    pageFlag = false;
                    $('.msg-page-a').hide();
                }
                var str = "";
                for (var i = 0; i < count; i++) {
                    var type = list[count - i - 1].type;
                    var comment = JSON.parse(list[count - i - 1].content);
                    var userdata = comment.userdata;
                    if (userdata.exct && userdata.exct != null && userdata.exct != undefined) {
                        var nickname = userdata.exct.nk;
                        var uid = userdata.exct.uid;
                        var logourl = userdata.exct.logourl;
                        var context = comment.context;
                        context = context.split('-{ip}-');
                        context = context[0];
                        context = msgFilter(context);
                        str += '<li>';
                        str += '<div class="barrage-msg-user"><b>' + nickname + '</b>：<span class="barrage-msg-word">' + context + '</span></div>';
                        str += '</li>';
                    }
                }
                $barrageMsg.prepend(str);
                if (page == 0) {
                    $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                    $scrollbar.data("plugin_tinyscrollbar").update('bottom');
                } else {
                    $scrollbar.data("plugin_tinyscrollbar").update();
                }
                page = data.next;
            });
    };
    $(function () {
        getCommentInfo();
    });
    document.onkeydown = function (event) {
        e = event ? event : (window.event ? window.event : null);
        if (e.keyCode == 13)
            $('.msg-send-btn').click();
    };
};

function live_mobile() {
    var selsctBox = function (tag) {
        if (tag == 'msg') {
            $(".chat-box").css("display", "block");
            $(".answer-box").css("display", "none");
            $("#msg").css("background-color", "#00479D");
            $("#msg").css("color", "white");
            $("#msg").css("border-color", "#00479D");
            $("#answer").css("background-color", "");
            $("#answer").css("color", "#666666");
            $("#answer").css("border-color", "#666666");
        } else {
            $(".chat-box").css("display", "none");
            $(".answer-box").css("display", "block");
            $("#msg").css("background-color", "");
            $("#msg").css("color", "#666666");
            $("#msg").css("border-color", "#666666");
            $("#answer").css("background-color", "#00479D");
            $("#answer").css("color", "white");
            $("#answer").css("border-color", "#00479D");
        }
    };

    $(".pop-Box .close").click(function () {
        $(".pop").css("display", "none");
    });


    $('.bottom-other-mobile').css("display", "");


    $('#msg').click(function () {
        selsctBox("msg");
    });
    $('#answer').click(function () {
        selsctBox("answer");
    });


    var llConfig = liveConfig.getConfig();
    var lids = llConfig.lids;
    pid = (pid) ? pid : 0;

    if (pid == null) {
        console.log('请设定默认播放资源');
    }
    //设置播放器
    new ysyPlayer({
        playerid: 'player', //放入播放器的容器元素的ID
        appid: llConfig.appid,
        lid: lids[pid].id,
        live: lids[pid].live,
        vr: lids[pid].vr,
        setOptions: {
            width: '100%', //播放器的宽度
            height: '100%', //播放器的高度
            poster: 'http://e.changan.com.cn/eado-xt2018_2/images/pcxt/wap/yd_mobile.jpg',
            autostart: 0,
            errorMsg: ''
        }
    });
    if (!lids[pid].vr) {
        $(".full-screen-btn").hide();
    }
    //全屏设置
    setTimeout(function () {
        if ($('.video-error').length && $('.video-error').length > 0) {
            $(".full-screen-btn").hide();
        }
    }, 500);
    var isFull = false;

    function fullsc() {
        if (!lids[pid].vr) {
            return;
        }
        if ($('.video-error').length && $('.video-error').length > 0) {
            return;
        }
        if (isFull) {
            if (isLandscape()) {
                //alert("请在坚屏模式下点击回复小窗播放");
                //return;
            }
            $(".hide-by-full").show();
            $('.player-box').addClass('player-box-a');
            $('.player-box').removeClass('player-box-b');
            $('#videoBox').addClass('video-box-a');
            $('#videoBox').removeClass('video-box-b');
            $('#videoBox').css('height', '');
            $('#videoBox').css('padding', '');
            $("#fullBtn").addClass('full');
            $("#fullBtn").removeClass('small');
            $('.live-container').removeClass('video-box-full');
            isFull = false;
        } else {
            $(".hide-by-full").hide();
            $('.player-box').addClass('player-box-b');
            $('.player-box').removeClass('player-box-a');
            $('#videoBox').addClass('video-box-b');
            $('#videoBox').removeClass('video-box-a');
            //$("#fullBtn").html('<i class="glyphicon glyphicon-resize-small"></i></a>');
            $("#fullBtn").removeClass('full');
            $("#fullBtn").addClass('small');
            $('.live-container').addClass('video-box-full');
            isFull = true;
        }
    }

    //videoFullScreen
    $(".full-screen-btn").click(fullsc);

    function orient() {
        if (isLandscape() && !isFull) {
            fullsc();
        } else
        //全屏时,转为竖屏,退出全屏
        if (!isLandscape() && isFull) {
            fullsc();
        }
    }

    //用户变化屏幕方向时调用
    $(window).bind('orientationchange', function (e) {
        orient();
    });
    orient();

    //聊天用户接入例子
    var uid = userAccount.getUID();
    var logourl = 'images/visitor.jpg'; //用户头像，可以使用网站或微信等得到用户再取相应值
    var page = 0;
    var pageFlag = true;
    var pageCount = 20;
    var msgSwiper = new Swiper4('.msg-swiper', {
        scrollbar: {
            el: '.swiper-scrollbar',
            dragSize: 30,
        },
        direction: 'vertical',
        slidesPerView: 'auto',
        //scrollbarHide: true,
        freeMode: true,
        observer: true,
        observeParents: true,
        onSetTranslate: function (swiper, translate) {
            var oldTranslate = sessionStorage.getItem('oldTranslate');
            if (translate > oldTranslate) {
                $('body').addClass('noselect');
            } else {
                $('body').removeClass('noselect');
                $('.barrage-more').attr('data-noselect', '0').html('暂无最新消息').hide();
            }
        },
        onTouchEnd: function (swiper) {
            if (swiper.isBeginning && page != 0)
                getOldCommentInfo();
        }
    });

    $('.msg-send-btn').on('click', function () {
        //发消息的时候为了保证发送的json完整，用户的昵称中特殊符号需要转义
        var ctcontent = $('input[name=ct]').val();
        var ct = msgFilter(ctcontent);
        if ($.trim($('input[name=ct]').val()) == '')
            return false;
        $('input[name=ct]').val('');
        if (isclick == 1 || timerSend < 10 || ct.indexOf('*') >= 0) {
            userAccount.getSendMsgOrder(function (resultUName) {
                var uname = resultUName;//userAccount.getUserNickName()
                // var uname = userAccount.getUserNickName();
                var $barrageMsg = $('.barrage-msg');
                var str = '<li class="swiper-slide">';
                str += '<div class="barrage-msg-user color-fff">' + uname + '：<span class="barrage-msg-word">' + ctcontent + '</span></div>';
                str += '</li>';
                $barrageMsg.append(str);
                useBarrage.popMsg(ctcontent);//弹幕输出消息
                $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                msgScrollBottom();
                return false;
            })
            return false;
        }
        sendTimeer();

        ct = msgFilter(ct);
        $.get('php/ip.php', {}, function (res) {
            userAccount.getSendMsgOrder(function (resultUName) {
                var uname = resultUName;//userAccount.getUserNickName()
                // var uname = userAccount.getUserNickName();//
                var $barrageMsg = $('.barrage-msg');
                var str = '<li class="swiper-slide">';
                str += '<div class="barrage-msg-user color-fff">' + uname + '：<span class="barrage-msg-word">' + ct + '</span></div>';
                str += '</li>';
                $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                $barrageMsg.append(str);
                if (res.code == 200) {
                    ysyChat.sendMessage({
                        type: 'msg',
                        content: ct.substr(0, 50) + '-{ip}-' + res.ip,
                        userdata: '{"exct":{"nk":"' + uname + '","logourl":"' + window.logourl + '","uid":"' + window.uid + '"}}',
                    });
                }
                msgScrollBottom();
            });
        }, 'json')
    });

    $('.barrage-more').on('click', function () {
        $('body').removeClass('noselect');
        msgScrollBottom();
        $(this).attr('data-noselect', '0').html('暂无最新消息').hide();
    })

    function quotationMarks(str) {
        str = str.replace(/\\/g, '\\\\');
        str = str.replace(/"/g, '\\\"');
        return str;
    }

    function msgScrollBottom() {
        var barrageMsgHeight = $('.msg-swiper').innerHeight() * 2;
        if (barrageMsgHeight != null) {
            //msgSwiper.setTranslate(-barrageMsgHeight);
            msgSwiper.update();
            msgSwiper.slideTo($('.msg-swiper li').length);
            var oldTranslate = msgSwiper.getTranslate(); //getWrapperTranslate();
            sessionStorage.setItem('oldTranslate', oldTranslate);
        }
    }

    function getCommentInfo() {
        ysyChat.init({
            appid: llConfig.appid,
            uid: uid,
            topic: llConfig.topic,
        }, function (data) {
            if (data.attribute) {
                var watched_count = data.attribute.watched_count;
                var watching_count = data.attribute.watching_count;
                //根据人数设置用户昵称
                userAccount.setUserNickName(watched_count);
                userAccount.getOnLineNum(function (count) {
                    $('#watch-count').text(count);
                });
                if (page == 0) {
                    getOldCommentInfo();
                }
            }
            if (data.type == 'msg' || data.type == 'redpack' || data.type == 'gift') {
                var data = JSON.parse(data.content);
                var userdata = data.userdata;
                var el, li, i, msgArr = [];
                el = document.querySelector('.barrage-msg');
                li = document.createElement('li');
                li.classList.add('swiper-slide');

                if (userdata.exct && userdata.exct != null && userdata.exct != undefined) {
                    var nk = userdata.exct.nk;
                    var uid = userdata.exct.uid;
                    var logourl = userdata.exct.logourl;
                    var context = data.context;
                    context = context.split('-{ip}-');
                    context = context[0];
                    context = msgFilter(context);

                    //弹幕输出消息
                    useBarrage.popMsg(context);
                    if (uid != window.uid) {
                        li.innerHTML = '<div class="barrage-msg-user color-fff">' + nk + '：<span class="barrage-msg-word">' + context + '</span></div>'
                    } else {
                        $('body').removeClass('noselect');
                    }
                }
                el.appendChild(li, el.childNodes[0]);

                //评论框滚动条置低
                var oldnoselect = parseInt($('.barrage-more').attr('data-noselect'));
                if ($('body').hasClass('noselect')) {
                    var newnoselect = oldnoselect + 1;
                    $('.barrage-more').html(newnoselect + '条新消息').show();
                    $('.barrage-more').attr('data-noselect', newnoselect);
                } else {
                    $('.barrage-more').attr('data-noselect', 0).html('暂无最新消息').hide();
                    msgScrollBottom();
                }
                return false;
            }
            if (data.type == 'system' || data.type == 'vote' || data.type == 'questionnaire') {
                var data = JSON.parse(data.content);
                if ('refresh' == data.refresh) {
                    var tmp = Math.floor(Math.random() * 5 + 1) * 1000;
                    setTimeout(function () {
                        window.location.reload();
                    }, tmp);
                }
            }
        })
    }

    function getOldCommentInfo() {
        if (pageFlag && pageFlag == true) {
            ysyChat.gethistorymsg({
                "start": page,
                "count": pageCount,
                "type": "msg,redpack,gift"
            }, function (data) {
                var list = data.list;
                var count = data.count;
                if (count < pageCount) {
                    pageFlag = false;
                }
                var str = "";
                for (var i = 0; i < count; i++) {
                    var type = list[count - i - 1].type;
                    var comment = JSON.parse(list[count - i - 1].content);
                    var userdata = comment.userdata;
                    if (userdata.exct && userdata.exct != null && userdata.exct != undefined) {
                        var nickname = userdata.exct.nk;
                        var uid = userdata.exct.uid;
                        var logourl = userdata.exct.logourl;
                        var context = comment.context;
                        context = context.split('-{ip}-');
                        context = context[0];
                        context = msgFilter(context);
                        str += '<li class="swiper-slide">';
                        str += '<div class="barrage-msg-user color-fff">' + nickname + '：<span class="barrage-msg-word">' + context + '</span></div>';
                        str += '</li>';
                    }
                }
                $('.barrage-msg').prepend(str);
                if (page == 0) {
                    msgScrollBottom();
                } else {
                    msgSwiper.onResize();
                    var barrageMsgHeight = $('.barrage-msg').height();
                    sessionStorage.setItem('oldTranslate', '-' + barrageMsgHeight);
                }
                page = data.next;
            })
        }
    }

    $(function () {
        getCommentInfo();
    });
}

//倒计时功能
function startDownCount(nowTimeStamp) {
    //console.log(nowTimeStamp);
    var dc = pageConfig.downCount,
        ele = dc.ele;

    if (!dc.use) {
        return;
    }
    var newTime = new Date();
    var intDiff = nowTimeStamp - Math.round(newTime.getTime() / 1000).toString();
    if (intDiff <= 0) {
        $(ele).hide();
        return;
    }

    window.setInterval(function () {
        var day = 0,
            hour = 0,
            minute = 0,
            second = 0; //时间默认值
        if (intDiff > 0) {
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        }
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        hour += day * 24;
        var countDownTime = hour + ":" + minute + ':' + second;
        $(ele).html(countDownTime);
        intDiff--;
    }, 1000);
}

//初始化直播
$.ajax({
    type: "post",
    url: liveConfig.configUrl,
    async: true,
    dataType: 'json',
    success: function (result) {
        // console.log(result);
        if (result.code == 200) {
            lc = eval('(' + result.data + ')');
            liveConfig = $.extend(true, liveConfig, lc);
            startDownCount(1535544000);//倒计时
            if (getDeviceType() == 'pc') {
                live_pc();
                useBarrage.init(30, 30 * 0.8, 'px');//初始化弹幕
            }
            else {
                live_mobile();
                useBarrage.init(5.0, 5.0 * 0.8, 'vw');//初始化弹幕
            }
        } else {
            console.log('get live config reuslt', result);
        }
    },
    error: function (e) {
        console.log('get live config error' + JSON.stringify(e));
    }
});
var answerIndex = 0, answerText = '';

$(function () {
    // $('.answer-area-list').eq(0).addClass('active');
    $.get('api.php?m=Api&c=Activity&a=getActivityStatus', {}, function (res) {
        $('.answer-area-list').eq(res.state).addClass('active');
        if (res.data && res.state == 3) {
            var table = $('.answer-area-list').eq(res.state).find('.winner-main-content table');
            $.each(res.data, function (i, v) {
                table.append(" <tr>\n" +
                    "<td>"+(i+1)+"</td>\n" +
                    "<td>"+v.user_name+"</td>\n" +
                    "<td>"+v.moble+"</td>\n" +
                    "<td>"+v.create_time+"</td>\n" +
                    "</tr>")
            })
        }
    }, 'json');

    $(".pop-Box .submit").click(function () {
        var regName = /^[\u4e00-\u9fa5]{2,4}$/;
        if (regName.test($(".pop #username").val()) == false) {
            alert("请输入正确的姓名");
            return;
        }
        var reMobile = /^1\d{10}$/;
        if (reMobile.test($(".pop #mobile").val()) == false) {
            alert("请输入正确的电话号码");
            return;
        }
        $(".pop").css("display", "none");
        $(".pop-load").css("display", "");
        $.post("api.php?m=Api&c=Activity&a=subAnswer", {
            username: $("#username").val(),
            moble: $("#mobile").val(),
            address: $('#address').val(),
            answer: answerIndex,
            answerText: answerText
        }, function (data) {
            $(".pop #username").val('');
            $(".pop #mobile").val('');
            $(".pop #address").val('');
            $(".pop").hide();
            if (data.status == 1)
                alert("提交信息成功！");
            else
                alert(data.msg);

        }, 'json');
    });
    $('.pop-Box .close').click(function () {
        $('.pop').hide();
    })
    $('.answer-btn').click(function () {
        if (answerIndex == 0) {
            alert('请选择答案');
            return;
        }
        $('.pop').show();
    })
    $(".answer-question ul li").each(function (index, element) {
        $(this).click(function () {
            answerIndex = $(this).index() + 1;
            answerText = $(this).text();
            $(this).addClass('active').siblings().removeClass('active');
        });
    });
})
